class VideoPlayer{
  constructor(dom,opts){
    this.timeChange = null;
    this.progressMouse = {
      mouseX:0,
      X:0, //x轴距离
      down:false, //是否按下
      up:false, //是否抬起
      range:0
    }
    this.voiceMouse = {
      Y:0, //Y轴距离
      down:false,//是否按下
      up:false,//是否抬起
      range:0
    }
    this.options = {
      fmt:opts.fmt?opts.fmt:'MM:SS',
      play:false, //是否播放
      autoplay:false, //是否自动播放
      muted:false, //是否静音播放
      loop:false, //循环
      volume:opts.volume, //音量
      ...opts
    }
    if(this.options.volume !== 0 && !this.options.volume || this.options.volume < 0 ||  this.options.volume>100){
      this.options.volume = 20
    }
    // 获取视频dom
    this.dom = document.querySelector(dom);
    this.videoDom = this.dom.querySelector("#video-player");
    const progressDot = this.dom.querySelector('.progress-contain').querySelector('#progress-dot');
    const progressContain = this.dom.querySelector('.progress-contain');
    this.maxLeftDot = (((progressContain.offsetWidth - progressDot.offsetWidth) / progressContain.offsetWidth)*100).toFixed(1);
    console.log('this.maxLeftDot',this.maxLeftDot)
  }
  // 初始化video
  initVideo(){
    // 声音模块
    const voiceContain = this.dom.querySelector('.voice-range');
    // 声音-点
    const voiceDot = voiceContain.querySelector("#voice-dot");
    // 声音的线
    const voiceLine = voiceContain.querySelector("#voice-has-line");
    // 声音滑块模块
    const voiceRangeContain = voiceContain.querySelector('#voice-range-contain');
    // 顶部最大值
    const maxTop = ((1 - (voiceDot.offsetHeight / voiceRangeContain.offsetHeight))*100).toFixed(0);
    // 视频遮罩
    const videoMask = this.dom.querySelector('.video-mask');
    // 视频控制模块
    const videoControl = this.dom.querySelector('.video-control');
    // 点击播放键
    videoMask.addEventListener('click',this.play_video.bind(this),false)
    // 点击底部播放键
    videoControl.querySelector('#video-play').addEventListener('click',this.play_video.bind(this))
    // 点击暂停视频
    this.dom.querySelector('.video-wrap').addEventListener('click',this.pause_video.bind(this));
    // 点击底部暂停视频
    videoControl.querySelector('#video-pause').addEventListener('click',this.pause_video.bind(this));
    //成功获取资源长度
    this.videoDom.addEventListener('loadedmetadata',this.loadedmetadata.bind(this));
    // 监听视频开始播放
    this.videoDom.addEventListener("play",this.videoIsPlay.bind(this));
    // 监听视频暂停
    this.videoDom.addEventListener("pause",this.videoIsPause.bind(this));
    // 播放时间改变
    this.videoDom.addEventListener("timeupdate",this.timeupdate.bind(this));
    // 播放结束
    this.videoDom.addEventListener('ended',this.ended.bind(this));
    // 监听音量改变
    this.videoDom.addEventListener("volumechange",this.volumeChange.bind(this));
    // 监听底部声音按钮点击
    this.dom.querySelector('.video-icon').addEventListener('click',this.voiceIconClick.bind(this))
    // 查找开始。当用户开始移动/跳跃到音频/视频中新的位置时触发
    // this.videoDom.addEventListener("seeking",this.seeking.bind(this));
    // 按下进度条
    this.dom.querySelector('.progress-contain').addEventListener('mousedown',this.progressMouseDown.bind(this));
    // 按下声音进度条
    this.dom.querySelector("#voice-range-contain").addEventListener("mousedown",this.voiceMouseDown.bind(this))
    // 监听移动
    document.addEventListener('mousemove',this.progressMouseMove.bind(this))
    // 监听抬起鼠标
    document.addEventListener('mouseup',this.progressMouseUp.bind(this));
    const playbackRateUl = this.dom.querySelector(".speed-contain .speed-list ul");
    const liList = this.dom.querySelector(".speed-contain .speed-list ul").getElementsByTagName('li');
    // console.log('liList',liList);
    // 设置视频属性
    this.videoDom.setAttribute('x-webkit-airplay','allow');
    this.videoDom.setAttribute('x5-video-player-type','h5');
    this.videoDom.setAttribute('webkit-playsinline','true');
    this.videoDom.setAttribute('playsinline','true');
    // 判断初始化是否为自动播放
    if(this.options.autoplay){
      this.videoDom.autoplay = 'autoplay';
      videoMask.querySelector("#play-screen-btn").style.display = "none";
      videoControl .querySelector('#video-play').style.display = 'none';
    }else{
      videoMask.querySelector("#pause-screen-btn").style.display = "none";
      videoControl.querySelector('#video-pause').style.display = 'none';
    }
    // 初始化音量

    // 判断最大值边界
    console.log('maxTop==>>',maxTop)
    if(this.options.volume>maxTop ){
      voiceDot.style.bottom = maxTop + "%";
    }else{
      voiceDot.style.bottom = this.options.volume + "%"
    }
    voiceLine.style.height = this.options.volume + "%";
    voiceContain.querySelector("#voice-val").innerText = this.options.volume;
    this.videoDom.volume = (this.options.volume/100).toFixed(2)
    // 判断静音
    if(this.options.muted){
      this.videoDom.muted = 'muted';
      this.mutedVoice();
    }
    this.videoDom.src = this.options.src;
    console.log(this.videoDom.volume)
    // 判断是否存在播放速度
    if(this.options.playbackRate){
      this.videoDom.playbackRate = this.options.playbackRate;
    }else{
      // 设置默认播放速率
      this.videoDom.playbackRate = 1;
    }
    if(!this.options.playbackRate){
      this.options.playbackRate = 1   
    }
    playbackRateUl.addEventListener('click',this.playbackRateUlHandle.bind(this))
    // 给播放速率列表设置默认class
    for(let i = 0;i<liList.length;i++){
      liList[i].index = i;
      liList[i].classList.remove('speed-active')
      if(this.options.playbackRate && this.options.playbackRate == liList[i].getAttribute('data-val')){
        this.videoDom.playbackRate = this.options.playbackRate;
        liList[i].classList.add('speed-active')
      }
      // liList[i].addEventListener('click',this.speedChange.bind(this))
    }
    console.dir(this.videoDom);
  }
  // 视频已经开始播放
  videoIsPlay(e){
    this.options.play = true;
    const videoMask = this.dom.querySelector('.video-mask');
    const videoControl = this.dom.querySelector('.video-control');
    // 将暂停按钮变为播放键
    videoMask.querySelector('#play-screen-btn').style.display = 'none';
    videoControl.querySelector('#video-play').style.display = 'none';
    // 显示播放按钮
    videoControl.querySelector('#video-pause').style.display = 'block';
    videoMask.querySelector('#pause-screen-btn').style.display = 'none';
    videoMask.style.display = 'none';
  }
  // 视频已经暂停
  videoIsPause(e){
    this.options.play = false;
    const videoMask = this.dom.querySelector('.video-mask');
    const videoControl = this.dom.querySelector('.video-control');
    // 显示暂停按钮变为播放键
    videoMask.querySelector('#play-screen-btn').style.display = 'block';
    videoControl.querySelector('#video-play').style.display = 'block';
    this.dom.querySelector('.video-mask').style.display = 'block';
    videoControl.querySelector('#video-pause').style.display = 'none';
  }
  //视频播放结束
  ended(e){
    const progressDot = this.dom.querySelector('.progress-contain').querySelector('#progress-dot');
    progressDot.style.left = this.maxLeftDot + "%";
  }
  // 播放速率改变
  playbackRateUlHandle(e){
    const speed = e.target.getAttribute("data-val")*1;
    const liList = this.dom.querySelector(".speed-contain .speed-list ul").getElementsByTagName('li');
    for(let i = 0 ;i<liList.length;i++){
      liList[i].classList.remove('speed-active')
      if(i == e.target.index){
        liList[i].classList.add('speed-active');
        this.videoDom.playbackRate = speed
      }
    }
    // e.target.
    console.log('xxxx==>>',e.target)
  }
  // 播放时间改变
  timeupdate(e){
    if(this.progressMouse.down){
      return
    }
    if(this.timeChange !== e.target.currentTime){
      const videoControl = this.dom.querySelector('.video-control');
      const time = this.formatSeconds(e.target.currentTime,this.options.fmt);
      const nowTimeDom = videoControl.querySelector('#now-time');
      nowTimeDom.innerText =  time;
      const range = ((e.target.currentTime/e.target.duration)*100).toFixed(1);
      const progressDot = this.dom.querySelector('.progress-contain').querySelector('#progress-dot');
      const progressPrev = this.dom.querySelector('.progress-contain').querySelector('#prevPlay');
      progressPrev.style.width = range + "%"
      if(range>=this.maxLeftDot){
        console.log('判断了')
        progressDot.style.left = this.maxLeftDot + "%";
      }else{
        progressDot.style.left = range + "%";
      }
    }
    this.timeChange = e.target.currentTime;
  }
  // 点击声音按钮
  voiceIconClick(){
    console.log('点击底部声音按钮',this.options.muted);
    if(this.options.muted){
      this.options.muted = false;
    }else{
      this.options.muted = true;
      
    }
    this.videoDom.muted = this.options.muted
    this.mutedVoice()
    this.videoDom.muted = this.options.muted;
  }
  volumeChange(e){
    // 改变音量
    console.log('改变音量',e.target.volume);
    const voiceContain = this.dom.querySelector('.voice-range')
    const voiceDom = this.dom.querySelector("#voice-range-contain");
    const voiceHasLineDom = voiceDom.querySelector("#voice-has-line");
    const voiceDot = voiceDom.querySelector("#voice-dot");
    voiceContain.querySelector("#voice-val").innerText = (e.target.volume * 100).toFixed(0);
    voiceDot.style.bottom = ((((voiceDom.offsetHeight - voiceDot.offsetHeight) * e.target.volume) / voiceDom.offsetHeight)*100).toFixed(1) + "%";
    console.log(voiceDot.style.bottom)
    if(e.target.volume == 0){
      voiceHasLineDom.style.height = 0;
    }else{
      voiceHasLineDom.style.height = (e.target.volume * 100).toFixed(0) + "%";
    }
    this.options.volume = (e.target.volume * 100).toFixed(0);
    // this.videoDom.muted = this.options.muted;
    this.mutedVoice()
  }
  // 将音量图标改为静音
  mutedVoice(){
    if(this.options.muted){
      this.dom.querySelector('.video-icon').classList.remove('icon-shengyin');
      this.dom.querySelector('.video-icon').classList.add('icon-jingyin1');
    }else{
      this.dom.querySelector('.video-icon').classList.remove('icon-jingyin1');
      this.dom.querySelector('.video-icon').classList.add('icon-shengyin');
    }
    
  }
  // 播放速率改变
  speedChange(e){
    const liList = this.dom.querySelector(".speed-contain .speed-list ul").getElementsByTagName('li');
    const speed = e.target.getAttribute("data-val")*1;
    for(let i = 0 ;i<liList.length;i++){
      liList[i].classList.remove('speed-active')
      if(i == e.target.index){
        console.log('得到')
        liList[i].classList.add('speed-active');
        this.videoDom.playbackRate = e.target.getAttribute('data-val')
      }
    }
    // this.videoDom.
    console.log(speed,e.target.index)
  }
  // 获取视频长度
  loadedmetadata(e){
    const time = this.formatSeconds(e.target.currentTime,this.options.fmt);
    // 视频控制
    const videoControl = this.dom;
    const timeWholeDom = videoControl.querySelector("#time-whole");
    const nowTimeDom = videoControl.querySelector("#now-time");
    // 设置视频长度
    timeWholeDom.innerText =  this.formatSeconds(e.target.duration,this.options.fmt);
    // 设置当前播放时间
    nowTimeDom.innerText =  time;
    console.log(e.target.duration)
    
  }
  // 播放视频
  play_video(){
    this.videoDom.play()
  }
  // 暂停视频
  pause_video(){
    this.videoDom.pause()
  }
  // 重置视频
  reload_video(){
    this.videoDom.load()
  }
  // 进度条鼠标移动
  progressMouseMove(e){
    // 视频进度条鼠标移动
    if(this.progressMouse.down){
      const controlContainDom = this.dom.querySelector('.progress-contain');
      const dot = this.dom.querySelector('.progress-contain').querySelector('#progress-dot');
      const progressPrev = controlContainDom.querySelector('#prevPlay');
      const {x} = e;
      const {left,width} = controlContainDom.getBoundingClientRect();
      if(this.progressMouse.mouseX !== x){
        // console.log('进度条移动')
        const offsetX = (x - left);
        // console.log('offsetX:',offsetX)
        // 设置播放原点位置
        // 判断最大最小值
        if(offsetX<=0){
          controlContainDom.querySelector('#progress-dot').style.left = 0;
          progressPrev.style.width = 0;
          this.progressMouse.range = 0;
        }else if(offsetX>=(width - dot.offsetWidth)){
          controlContainDom.querySelector('#progress-dot').style.left = this.maxLeftDot + "%"
          progressPrev.style.width = '100%';
          this.progressMouse.range = 100;
        }else{
          const range = ((offsetX/width)*100).toFixed(1);
          // console.log('range',range)
          controlContainDom.querySelector('#progress-dot').style.left = range + "%";
          progressPrev.style.width = range + '%';
          this.progressMouse.range = range;
        }
      }
      this.progressMouse.mouseX = x
    }
    this.voiceMouseMove(e) 
  }
  voiceMouseMove(e){
    // 声音进度条鼠标移动
    if(this.voiceMouse.down){
      const voiceDom = this.dom.querySelector("#voice-range-contain");
      const voiceDot = voiceDom.querySelector("#voice-dot");
      const {top,height} = voiceDom.getBoundingClientRect()
      const {y} = e;
      const maxTop = voiceDot.offsetHeight;
      const maxBottom = top + voiceDom.offsetHeight;
      if(y<=(top + maxTop)){
        this.videoDom.volume = 1;
      }else if(y>=maxBottom){
        this.videoDom.volume = 0;
      }else{
        this.videoDom.volume = (((height - y + top) / (height - maxTop))).toFixed(2);
      }
      
    }
  }
  // 进度条鼠标按下
  progressMouseDown(e){
    const controlContainDom = this.dom.querySelector('.progress-contain');
    const rangeWidth = controlContainDom.offsetWidth;
    const dotDom = controlContainDom.querySelector('#progress-dot')
    const {x} = e;
    this.progressMouse.mouseX = x
    const {left,width} = controlContainDom.getBoundingClientRect();
    const progressPrev = controlContainDom.querySelector('#prevPlay');
    const offsetX = (x - left);
    this.progressMouse.X = offsetX;
    this.progressMouse.down = true
    const range = ((offsetX/width)*100).toFixed(1);
    // 判断最大值
    if(offsetX>(rangeWidth - dotDom.offsetWidth )){
      dotDom.style.left = (((rangeWidth - dotDom.offsetWidth)/rangeWidth )*100).toFixed(1) + "%";
      progressPrev.style.width = "100%";
      this.progressMouse.range = 100;
    }else{
      dotDom.style.left = range + "%";
      progressPrev.style.width = range + "%";
      this.progressMouse.range = range;
    }
  }
  // 声音进度条鼠标按下
  voiceMouseDown(e){
    this.voiceMouse.down = true;
    const voiceDom = this.dom.querySelector("#voice-range-contain");
    const voiceDot = this.dom.querySelector("#voice-dot");
    const {top,height} = voiceDom.getBoundingClientRect()
    const {y} = e;
    const rangeBack = (y - top);
    const maxTop = voiceDot.offsetHeight;
    const maxBottom = top + voiceDom.offsetHeight;
    console.log('maxBottom',maxBottom)
    if(rangeBack<=maxTop){
      this.videoDom.volume = 1
    }else if(y>=maxBottom){
      this.videoDom.volume = 0
    }else{
      this.videoDom.volume = (((height - y + top) / (height - maxTop))).toFixed(2);
    }
  }
  // 进度条鼠标抬起
  progressMouseUp(e){
    if(this.progressMouse.down){
      this.progressMouse.down = false
      // 播放进度
      const range = this.progressMouse.range*1;
      const nowTime = this.videoDom.duration * (range/100);
      this.videoDom.currentTime = nowTime
    }
    // 判断是否按下声音进度条
    if(this.voiceMouse.down){
      this.voiceMouse.down = false;
    }
  }
  // 销毁视频，取消点击事件
  dispose_video(){
    this.dom.querySelector('.video-mask').removeEventListener('click',this.play_video.bind(this),false)
  }
  //将秒数转换为时分秒格式-------dd:HH:MM:SS 天:小时:分钟:秒
  formatSeconds(value,fmt) {
    let ret;
    var theTime = Math.round(value);// 秒
    const opt = {
      "d+": Math.floor((theTime / 3600)/24).toString(),            // 日
      "H+": Math.floor(theTime / 3600).toString(),           // 时
      "M+": Math.floor((theTime / 60 % 60)).toString(),         // 分
      "S+": Math.floor((theTime % 60)).toString()         // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;;
  }
  // 判断是否存在class
  hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
   }
}